package org.xtb.CS_3;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class AppServerHandler extends Thread {
    private Socket clientSocket;
    private PrintWriter appOut;
    private BufferedReader appIn;
    private static final String END_FLAG = "###END###";


    public AppServerHandler(Socket clientSocket) {
        this.clientSocket = clientSocket;
    }

    public void run() {
        try {
            appOut = new PrintWriter(clientSocket.getOutputStream(), true);
            appIn = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

            // 连接数据库服务器
            Socket dbSocket = new Socket("localhost", 8890);
            PrintWriter dbOut = new PrintWriter(dbSocket.getOutputStream(), true);
            BufferedReader dbIn = new BufferedReader(new InputStreamReader(dbSocket.getInputStream()));

            String inputLine;
            while ((inputLine = appIn.readLine()) != null) {
                System.out.println("客户端请求：" + inputLine);

                // 将请求转发给数据库服务器
                dbOut.println(inputLine);

                // 接收数据库服务器的响应并发送给客户端
                String dbResponse;
                while ((dbResponse = dbIn.readLine()) != null) {
                    if (dbResponse.equals(END_FLAG)) {
                        break;
                    }
                    appOut.println(dbResponse);
                }

                appOut.println(END_FLAG);
            }

            appOut.close();
            appIn.close();
            clientSocket.close();
            dbOut.close();
            dbIn.close();
            dbSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}